#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include "Init.hpp"
#include "log.hpp"

extern Init it;
extern Log lg;

class Task
{
public:
    Task(){};

    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : sockfd_(sockfd), ip_(clientip), port_(clientport)
    {
    }

    void result()
    {

        char buffer[1024];
        int n = read(sockfd_, buffer, sizeof(buffer) - 1);
        if (n < 0)
        {
            lg(Fatal, "server read error, sockfd:%d,errno:%d, error string:%s", sockfd_, errno, strerror(errno));
        }
        else if (n == 0)
        {
            lg(Info, "client quit,sockfd: %d", sockfd_);
        }
        else
        {
            buffer[n] = 0;
            // std::cout << "client say# " << buffer << std::endl;

            // cout<<"client close sockfd"<<endl;
            // sleep(5);

            std::string echo_message = it.translate(buffer);
            n = write(sockfd_, echo_message.c_str(), echo_message.size());
            if (n < 0)
            {
                lg(Fatal, "server write error, sockfd:%d,errno:%d, error string:%s", sockfd_, errno, strerror(errno));
            }
        }

        close(sockfd_);
    }

private:
    int sockfd_;
    uint16_t port_;
    std::string ip_;
};